package com.usian.filter;

import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @projectName: 2210A-project1
 * @package: com.usian.filter
 * @className: MyFilter
 * @author: 莫洪维
 * @email: 1204315800@qq.com
 * @description: 网关过滤器,过滤前端发送的请求,登录路径直接放行,
 * 携带token,token没有过期放行,其余的都拦截并返回401
 * @date: 2023/8/22 10:35
 */
@Component
@Slf4j
public class MyFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //设置登录路径
        String loginUrl = "/frontEnd/login";
        //获取request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径
        String path = request.getURI().getPath();
        //判断是否是登录路径
        if (path.contains(loginUrl)){
            log.info("登录路径,直接放行");
            return chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().getFirst("token");
        log.info("token:{}",token);
        //判断token是否为空
        if (token == null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }else {
            try {
                //判断token是否过期
                boolean b = JWTUtil.verify(token, "1234".getBytes());
                if (b){
                    return chain.filter(exchange);
                }else {
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
            } catch (Exception e) {
                e.printStackTrace();
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
